package concurrentwrite.callback.run;

import me.prettyprint.cassandra.service.CassandraHost;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.factory.HFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by IntelliJ IDEA.
 * User: tuyuri
 * Date: 01/06/2012
 * Time: 00:07
 * To change this template use File | Settings | File Templates.
 */
public class Main {
    Object result;
    int cnt = 0;
    long begTest, endTest;
    int k = 0;
    private Cluster cluster;

    public Main() {
        begTest = new java.util.Date().getTime();
    }

    public void callBack(Object result) {
        System.out.println("result " + result);
        this.result = result;
        if (++cnt == k) {
            Double secs = new Double((new java.util.Date().getTime() - begTest) * 0.001);
            System.out.println("run time " + secs + " secs");
            cluster.getConnectionManager().shutdown();
            System.exit(0);
        }
    }

    public void run() {
        DataQueue.init();
        k = DataQueue.dataFilesQueue.size();
        int nrOfProcessors = 4;
//        int nrOfProcessors = Runtime.getRuntime().availableProcessors();
        ExecutorService es = Executors.newFixedThreadPool(nrOfProcessors);
        cluster = HFactory.getOrCreateCluster("Adlog cluster", "192.168.23.84:9160");
        CassandraHost cassandraHost2 = new CassandraHost("192.168.23.85", 9160);
        CassandraHost cassandraHost3 = new CassandraHost("192.168.23.86", 9160);
        //cluster.addHost(cassandraHost2, true);
        //cluster.addHost(cassandraHost3, true);
        for (int i = 0; i < k; i++) {
            WriteLogByFileTask task = new WriteLogByFileTask(i);
            task.setCaller(this);
            task.setFilePath(DataQueue.dataFilesQueue.poll());
            task.setCluster(cluster);
            es.submit(task);
            // at this point after submitting the tasks the
            // main thread is free to perform other work.
        }
    }

    public static void main(String[] args) {
        long startTick = System.currentTimeMillis();
        new Main().run();
        System.out.println("exit after" + (System.currentTimeMillis() - startTick));
    }
}
